package com.uuj.dome.controller;

import com.uuj.dome.bean.UserEntity;
import com.uuj.dome.jsp.UserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * ClassName:LoginController
 * PACKAGE_NAME:com.uuj.dome.controller
 */
@RestController
@RequestMapping(value = "/user")
public class LoginController {

    @Autowired
    private UserJpa userJPA;

    @RequestMapping(value = "/login")
    public String login(UserEntity entity, HttpServletRequest request) {
        boolean flag = true;
        String result = "登录成功";

        //根据用户名查询用户是否存在
        Optional<UserEntity> userEntity = userJPA.findOne(new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("name"), entity.getName()));
                return null;
            }
        });
        // jdk新特性 userEntity.isPresent为false时对象是空的
        if (!userEntity.isPresent()) {
            flag = false;
            result = "用户不存在，登录失败";
            return result;
        }

        if (!userEntity.get().getPassword().equals(entity.getPassword())) {
            flag = false;
            result = "用户密码不相符，登录失败";
        }

        if (flag) {
            request.getSession().setAttribute("user", entity);
        }

        return result;
    }
}
